$(function() {
	getDatas();
});

function getDatas() {
	getMeasuresFinishRatio();
	getCompanyFinishRatio();
	getCompanyFinishRatioDetailDatas();
}

function getMeasuresFinishRatio() {
	$.getJSON("/rest/measures/getAllCounterMeasures",function(result){
		/**
		 * 各反措项目完成率
		 * 0:{finishRatio:97, order:1, name:"规范断路器本体三相不一致保护运行（调继〈2011〉6号）"}
		 * 1:{finishRatio:84, order:2, name:"220kV及以上系统变电站主变变高断路器失灵联跳变压器各侧断路器核查（调继 〈2011〉19号）"}
		 */
		initMeasuresFinishRatioChart(result);
		initMeasureItems(result);
	});
}

function getAllDateSource() {
	
}

function getCompanyFinishRatio() {
	$.getJSON("/rest/measures/getCompanyCounterMeasureDatas",function(result){
		/**
		 * 各分子公司反措完成率
		 * 0:{ratio:96, company:"广东"}
		 * 1:{ratio:95, company:"广西"}
		 */
		initCompanyFinishRatioChart(result);
	});
}

$('#detailTabPanel').click(function() {
	var w = $('#detailCaseTab').width() + "";
	$('#measureBars').css('width', w - 50);
	getSelectedMeasureDatas();
	y2LineBars.getChart().resize();
});

var legend=[];
var Bars=function(chartid){
	var colors = ['#7ECF51','#EECB5F','#9570E5','#E3935D','#E16757','#5793f3','#008B8B','#675bba'];
	var myChart = echarts.init(document.getElementById(chartid));	
	var option ={
			  dataZoom: [
			             {
			                 id: 'dataZoomX',
			                 type: 'inside',
			                 show: true,
			                 xAxisIndex: [0],
			                 filterMode: 'filter'
			             }		            
			         ],
			   title: {
			    },
			    tooltip: {
			        trigger: 'axis'
			    },
			    toolbox: {
			        feature: {
			           dataView: {
	                    	readOnly: false,
	                    	optionToContent:function(opt){
	                    		var axisData = opt.xAxis[0].data;
	                    	    var series = opt.series;
	                    	    var table = '<table border="1" style="width:100%;text-align:center"><tbody><tr>'
	                    	                 + '<td>'+opt.xAxis[0].name+'</td>';
	                    	    for(var j=0;j<series.length;j++){
	                    	    	table = table + '<td>' + series[j].name + '</td>';
	                    	    }
	                    	    for (var i = 0, l = axisData.length; i < l; i++) {
	                    	        table += '<tr>'
	                    	                 + '<td>' + axisData[i] + '</td>';
	                    	        for(var z=0;z<series.length;z++){
	                    	        	if(isNaN(parseInt(series[z].data[i]))){
	                    	        		table = table + '<td>' + '</td>';
	                    	        	}else{
	                    	        		table = table + '<td>' + series[z].data[i] + '</td>';
	                    	        	}
	                    	        }
	                    	    }
	                    	    table += '</tbody></table>';
	                    	    return table;
	                    	},
	                    	iconStyle:{
	                    		normal:{},
	                    		emphasis:{}
	                    	}
	                    },
			            restore: {show: true},
			            saveAsImage: {show: true}
			        }
			    },
			    grid: {
			        containLabel: true
			    },
			    legend: {
			    	data: []
			    },
			    xAxis: [{
			        type: 'category',
			        axisTick: {
			            alignWithLabel: true
			        },
			        data: []
			    }],
			    yAxis: [{
			        type: 'value',
			        name: '完成率',
			        min: 0,
			        max: 100,
			        position: 'right',
			        axisLabel: {
			            formatter: '{value}%'
			        },
			        axisLine: {
		                lineStyle: {
		                    color: colors[4]
		                }
		            }
			    }, {
			        type: 'value',
			        name: '数量',
			        min: 0,
			        position: 'left'
			    }],
			    series: []
		};
	this.show = function(){
		myChart.setOption(option);
	};
	this.getChart = function(){
		return myChart;
	};
	this.setArea=function(datas){
		option.xAxis[0].data=datas;
	};
	this.setSeries=function(arr,legend,ratios){
		option.series.splice(0,option.series.length);
		option.series.push(
				{
			        name: '完成率',
			        type: 'line',			      
			        data: ratios
			    });
		option.series.push(
				{
			        name: '应反措',
			        type: 'bar',
			        yAxisIndex: 1,
			        data:arr[0],
			        label:{
						normal:{
							show:true,
							textStyle:{},
							position:'top'
						},
						emphasis:{
							show:true,
							textStyle:{}
						}
					},
			        itemStyle:{
		                 normal:{color:colors[0]}
		             }
			    });
		option.series.push(
				{
			        name: '已完成',
			        type: 'bar',
			        yAxisIndex: 1,		        
			        data: arr[1],
			        label:{
						normal:{
							show:true,
							textStyle:{},
							position:'top'
						},
						emphasis:{
							show:true,
							textStyle:{}
						}
					},
			        itemStyle:{
		                 normal:{color:colors[1]}
		             }
			    });
		option.legend.data=legend;
		for(var i=2; i<arr.length; i++) {
			var colorNum;
			if(i > colors.legth) {
				colorNum = i - colors.legth;
			} else {
				colorNum = i;
			}
			option.series.push(
			{
				name: legend[i],
				type: 'bar',
				yAxisIndex: 1,		        
				data: arr[i],
				label:{
					normal:{
						show:true,
						textStyle:{},
						position:'top'
					},
					emphasis:{
						show:true,
						textStyle:{}
					}
				},
				itemStyle:{
					normal:{color:colors[colorNum]}
				}});
		}
	};
};

var y2LineBars=new Bars("measureBars");
var categoryValue;
var category;
var companyFinishDetailDatas;
function getCompanyFinishRatioDetailDatas(){
	$.getJSON("/rest/measures/getCounterMeasures",function(result){
		/**
		 * 0:{name:"规范断路器本体三相不一致保护运行（调继〈2011〉6号）",value:
		 * 															{0:{name: "广东", value: 
		 * 																					0:{name: "应反措", value: 254}
		 *                                                                                  1:{name: "已完成", value: 254}
		 *                                                                                  2:{name: "至2016年底完成数", value: 0}
		 *                                                                                  3:{name: "至2015年底完成数", value: 254}}}}
		 */
		companyFinishDetailDatas = result;
	});
}

function getSelectedMeasureDatas() {
	getCompanyFinishRatioDetailDatas();
	category = $("#protectCounterMeasureName_id").val();
	for(var i in companyFinishDetailDatas) {
		if(companyFinishDetailDatas[i].name == category) {
			categoryValue = companyFinishDetailDatas[i].value;
		}
	}
	initChartBarData();
}

var counterMeasuresChart;
function initMeasuresFinishRatioChart(data){
	var aindicators = [];
	var aps = [];
	for(var i in data){
		var obj = data[i];
			aindicators.push({name:obj.order, max: 100,min:0});
			aps.push(obj.finishRatio);		
	}
	var myDate = new Date();
	var now = myDate.getFullYear()+"年"+(Number(myDate.getMonth())+1)+"月"+myDate.getDate()+"日";
	counterMeasuresChart = new NormalRadar('totalDatas');
	counterMeasuresChart.getOption().title.text="至"+ now +"各反措项目完成情况";
	counterMeasuresChart
		.setIndicator(aindicators)
		.addData({name:'完成率',value:aps,label:{normal:{show:true,formatter: '{b}: {c}%'}}})
		.show();
}

function initCompanyFinishRatioChart(data){
	var aindicators = [];
	var aps = [];
	for(var i in data){
		var obj = data[i];
			aindicators.push({name:obj.company});
			aps.push(obj.ratio);		
	}
	var myDate = new Date();
	var now = myDate.getFullYear()+"年"+(Number(myDate.getMonth())+1)+"月"+myDate.getDate()+"日";
	counterMeasuresChart = new NormalRadar('subCompanyDatas');
	counterMeasuresChart.getOption().title.text="至"+ now +"各分子公司反措项目完成情况";
	counterMeasuresChart
		.setIndicator(aindicators)
		.addData({name:'完成率',value:aps,label:{normal:{show:true,formatter: '{b}: {c}%'}}})
		.show();
}

//加载项目标题
function initMeasureItems(data){
	$("#itemsid").empty();
	for(var i in data){
		var obj = data[i];
		$("#itemsid").append("<p>"+obj.order+"."+obj.name+"</p><br/>");
	}
}

function initChartBarData(){
	var ratios=[];
	var areas=[];
	var type=[];
	var arr = new Array();
	legend=[];
	for(var u in categoryValue) {
		areas.push(categoryValue[u].name);
	}
	if(categoryValue.length != 0) {
		var value = categoryValue[0].value;
		for(var i=0; i<value.length; i++) {
			legend.push(value[i].name);
		}
		var a = categoryValue[0].value.length;
		var b = categoryValue.length;
		for(var i=0; i<a; i++) {
			arr[i]=new Array(i);
			for(var j=0; j<b; j++) {
				type = categoryValue[j].value;
				arr[i][j]=type[i].value;
			}
		}
		for (var t=0; t<b; t++) {
			var ratio = (parseInt(arr[1][t]) / parseInt(arr[0][t]))*100;
			ratios.push(ratio.toFixed(2));
		}
	}
	y2LineBars.setArea(areas);
	y2LineBars.setSeries(arr,legend,ratios);
	y2LineBars.show();	
}
function initChart(){
	getCompanyFinishRatioDetailDatas();
	getDatas();
}
